#! /usr/bin/python
# -*- coding: utf-8 -*-

import os
from google.appengine.ext.webapp import template
import cgi
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
import urllib
import conf
import utils
import counters
import paper
import tagconfig
import antispam
import validator
import permission

class MainPage(webapp.RequestHandler):
    def get(self):
        cookieDict = utils.getXnCookieDict(self.request.cookies)
        is_logged_in = utils.validateXnCookies(cookieDict, conf.app_secret)
        callbackUrl = utils.getUrlPathQuery(self.request)
        if not is_logged_in:
            self.redirect("/login?" + urllib.urlencode({'url':callbackUrl}))
            return None
        xnuid = cookieDict['user']
        try:
            xnuid = int(xnuid)
        except ValueError:
            xnuid = 0

        #Santinize param op
        op = self.request.get('op')
        if not (op in ['new', 'edit']):
            op = 'new'
        paperId = self.request.get('pid')
        try:
            paperId = int(paperId)
        except ValueError:
            paperId = 0
        if op == 'edit' and paperId:
            paperModel = paper.readPaperById(paperId)
        else:
            paperModel = None
            
        category = ''
        title = ''
        content = ''
        errMsg = ''
        if paperModel:
            if not permission.hasEditPaperPermission(xnuid, paperModel.authorId):
                errMsg = '试图编辑别人的文章是不允许的！'
            else:
                category = paperModel.category
                title = paperModel.title
                filteredContent = antispam.filter(paperModel.content, htmlEncodingMode=True)
                if filteredContent == None:
                    errMsg = '文章内容过滤出错，请联系管理员'
                else:
                    content = filteredContent
        
        template_values = {
            'staticUrl': conf.staticUrl,
            'jsVersion': conf.jsVersion,
            'cssVersion': conf.cssVersion,
            'xnuid': xnuid,
            'isAdministrator': permission.isAdministrator(xnuid),
            'isLoggedIn': is_logged_in,
            'tinymceValidElements': tagconfig.tinymceValidElementsConfig(),
            'paperCategoryList': conf.paperCategoryList,
            'op': op,
            'callbackUrl': callbackUrl,
            'pid': paperId,
            'category': category,
            'title': title,
            'content': content,
            'sysPaperUrlHowToInputFormula': conf.sysPaperUrlHowToInputFormula,
            'sysPaperUrlCelebrating': conf.sysPaperUrlCelebrating,
            'sysPaperUrlFaq': conf.sysPaperUrlFaq,
            'sysPaperUrlSiteEvents': conf.sysPaperUrlSiteEvents,
            'sysPaperUrlHowToRss': conf.sysPaperUrlHowToRss,
            'paperStatusNormal': paper.paperStatusNormal,
            'paperStatusDraft': paper.paperStatusDraft,
            'errMsg': errMsg
        }
        path = os.path.join(os.path.dirname(__file__), 'pages/editpaper.html')
        self.response.out.write(template.render(path, template_values))

    def post(self):
        cookieDict = utils.getXnCookieDict(self.request.cookies)
        is_logged_in = utils.validateXnCookies(cookieDict, conf.app_secret)
        paperId = self.request.get('pid')
        #Santinize param op
        op = self.request.get('op')
        if not (op in ['new', 'edit', 'del']):
            op = 'new'
        callbackUrl = '/editpaper?op='
        if paperId:
            if op == 'edit':
                callbackUrl += op + '&pid=' + paperId
            else:
                #op == 'del' or 'new'(invalid)
                callbackUrl = '/mathml/readpaper?pid=' + paperId
        else:
            callbackUrl += 'new'
        if not is_logged_in:
            self.redirect("/login?" + urllib.urlencode({'url':callbackUrl}))
            return None
        
        xnuid = cookieDict['user']
        try:
            xnuid = int(xnuid)
        except ValueError:
            xnuid = 0

        try:
            paperId = int(paperId)
        except ValueError:
            paperId = 0
        errMsg = ''
        needReOpen = False
        if (op == 'edit' or op == 'del') and paperId:
            if op == 'edit':
                opName = '编辑'
            else:
                opName = '删除'
            paperModel = paper.readPaperById(paperId)
            if not paperModel:
                errMsg = '试图' + opName + '的文章不存在，请联系管理员！'
            else:
                if (op == 'edit' and permission.hasEditPaperPermission(xnuid, paperModel.authorId)) or ((op == 'del' and permission.hasDeletePaperPermission(xnuid, paperModel.authorId))):
                    pass
                else:
                    errMsg = '试图' + opName + '别人的文章是不允许的！'
                    if paperModel.pid != paperId:
                        errMsg = '数据发生不一致，请联系管理员'
        else:
            paperModel = paper.Paper()
        

        title = ''
        category = ''
        content = ''
        if op != 'del':
            title = self.request.get('title')
            category = self.request.get('category')
            content = self.request.get('content')
            #Filter the title & content
            titleValidator = validator.PureTextValidator(title)
            title = titleValidator.filter()
            filteredContent = antispam.filter(content)
            if filteredContent == None:
                errMsg = '内容过滤出错，保存失败，请联系管理员'
            else:
                content = filteredContent
            checkResult = paper.checkPaper(category, title, content)
            if checkResult != True:
                errMsg = checkResult
        
        if not errMsg:
            #save to datastore
            if op == 'new':
                counter = counters.AtomicCounter('paper')
                newPid = counter.AtomicInc()
                paperId = newPid
            
            if op == 'del':
                paperModel.status = paper.paperStatusDeleted
            else:
                paperModel.pid = paperId
                paperModel.category = category
                paperModel.title = title
                paperModel.content = content
                status = self.request.get('status')
                try:
                    status = int(status)
                    if status not in [paper.paperStatusNormal, paper.paperStatusDraft]:
                        status = paper.paperStatusDraft
                except ValueError:
                    status = paper.paperStatusDraft
                paperModel.status = status
                if op == 'new':
                    paperModel.authorId = xnuid
                #paperModel.createdTime = createdTime
                #paperModel.lastModifiedTime = lastModifiedTime
            
            paper.writePaper(paperModel)
            
            #send redirect to paper read page
            if op == 'del':
                #Redirect to HOME page afer deleting some paper
                self.redirect("/profile")
            else:
                self.redirect("/mathml/readpaper?" + urllib.urlencode({'pid':paperId}))
            return None
        else:
            #send redirect to paper edit page
            filteredContent = antispam.filter(content, htmlEncodingMode=True)
            if filteredContent == None:
                content = utils.htmlEncode(content)
                needReOpen = True
            else:
                content = filteredContent
            template_values = {
                'staticUrl': conf.staticUrl,
                'jsVersion': conf.jsVersion,
                'cssVersion': conf.cssVersion,
                'xnuid': xnuid,
                'isLoggedIn': is_logged_in,
                'tinymceValidElements': tagconfig.tinymceValidElementsConfig(),
                'paperCategoryList': conf.paperCategoryList,
                'op': op,
                'callbackUrl': callbackUrl,
                'pid': paperId,
                'category': category,
                'title': title,
                'content': content,
                'sysPaperUrlHowToInputFormula': conf.sysPaperUrlHowToInputFormula,
                'sysPaperUrlCelebrating': conf.sysPaperUrlCelebrating,
                'sysPaperUrlFaq': conf.sysPaperUrlFaq,
                'sysPaperUrlSiteEvents': conf.sysPaperUrlSiteEvents,
                'sysPaperUrlHowToRss': conf.sysPaperUrlHowToRss,
                'paperStatusNormal': paper.paperStatusNormal,
                'paperStatusDraft': paper.paperStatusDraft,
                'errMsg': errMsg,
                'needReOpen': needReOpen
            }
            path = os.path.join(os.path.dirname(__file__), 'pages/editpaper.html')
            self.response.out.write(template.render(path, template_values))

application = webapp.WSGIApplication(
                                     [('/editpaper', MainPage)],
                                     debug=True)
def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
